<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:OplusCms Cms基本設定
 *@param datetime 2012-01-07
 *@param author solgh
 ********************/
class Settings extends Admins_Controller {
  
  private $data=array();

  public function __construct(){
    parent::__construct();
    $this->data['currentPage']='settings';
    $this->load->model('settings_mdl');
    
    $this->load->model('languages_mdl');
    $this->data['language_query']=$this->languages_mdl->get_languages(array('status'=>1));
      $lan_get = 	$this->input->get('lan','');
      $lan_get = empty($lan_get) ? get_cookie('language') : $lan_get;
      if(empty($lan_get) || !in_array($lan_get,array('zh-tw','english'))){
          $lan_get = 'english';
      }
      $this->lang->load('page', $lan_get);
      set_cookie('language',$lan_get,time()+24*3600*30);
      $this->data['getlang'] = $lan_get;
    $this->data['lang'] =$this->lang->language;
  }
  
  public function index(){
    $this->get_list();
    $this->load->view('admins/settings_list_view',$this->data);
  }
  
  //獲取基本設置
  public function get_list(){
    $query=$this->settings_mdl->get_settings();
    $sdata=array();
    foreach($query->result_array() as $q){
      $sdata[$q['group']][]=array(
        'key'=>$q['key'],
        'value'=>$q['value'],
        'description'=>$q['description'],
        'content'=>$q['content']
      );
    }
    $this->data['lists']=$sdata;
  }
   //保存設置
   public function edit(){
      $settings=$this->input->post('settings');
      $result=0;
      foreach($settings as $set){
        $keys=$this->input->post($set.'_key');
        foreach($keys as $key){
          $value=$this->input->post($key.'_value');
          $description=$this->input->post($key.'_description');
          $content=$this->input->post($key.'_content');
          //判斷是否google_maps
          if($key=='google_maps'){
            $map_x=$this->input->post('map_x');
            $map_y=$this->input->post('map_y');
            $value=!empty($map_x) && !empty($map_y)?$map_x.'|'.$map_y:$value;
          }

          $data=array(
            'group'=>$set,
            'key'=>$key,
            'value'=>$value,
            'description'=>$description,
            'content'=>$content
          );
          $result+=$this->settings_mdl->edit_settings_by_keyGroup($data);
        }
      }
      $this->operator_log('編輯基本設定','修改',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      redirect("admins/settings");
   }
   
  //上傳主圖片.
  private function _upload_images($file_name='',$old_image=''){
    if(isset($_FILES[$file_name]['name']) && !empty($_FILES[$file_name]['name'])){
      $upload_path='uploads/setting/';
      Imagelib::mkdir_file($upload_path); //創建路徑
      $allowed_types=array('jpg','png','gif','jpeg','pdf','doc','docx');
      $max_size='80240000';
      $temp_file=$_FILES[$file_name]['tmp_name']; //臨時文件
      $f_name=$_FILES[$file_name]['name'];
      $f_size=$_FILES[$file_name]['size'];
      $x = explode('.', $f_name);
      $f_extention=strtolower(end($x));
      if(!empty($f_extention) && in_array($f_extention,$allowed_types) && $f_size<=$max_size){
        $filename = md5(uniqid(mt_rand())).'.'.$f_extention; //新名字
        $new_file_name=$upload_path.$filename;
        if(move_uploaded_file($temp_file,$new_file_name)){
          if(!empty($old_image) && file_exists($old_image)){
            Imagelib::delete_image($old_image); //刪除舊圖片.
            Imagelib::delete_thumb_image($old_image); //刪除舊圖片縮略圖.
          }
          return $new_file_name; //返回上傳后的新名字.
        }
      }
    }else{
      return $old_image;
    }
  }
  
   //添加設置
   public function add(){
      $this->load->view('admins/settings_form_view',$this->data);
   }
   
   //執行添加設置
   public function add_modify(){
    $this->_load_validation_rules();
    if ($this->form_validation->run() == FALSE){
      $this->data['error']=true;
      $this->load->view('admins/settings_form_view',$this->data);
    }else{
      $data=array(
        'group'=>$this->input->post('group'),
        'key'=>$this->input->post('key'),
        'value'=>$this->input->post('value'),
        'description'=>$this->input->post('description'),
        'content'=>$this->input->post('content')
      );
      $result=$this->settings_mdl->add_settings($data);
      $this->operator_log('新增基本設定','添加',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $result>0?$this->db->cache_delete('admins', 'settings'):'';
      $this->nsession->set_flashdata($notify, $msg);
      redirect("admins/settings");
     }
   }
   //驗證數據格式
   private function _load_validation_rules(){
//       $this->form_validation->set_rules('content','英文描述','trim|required|htmlspecialchars|max_length[100]');
      $this->form_validation->set_rules('description','描述','trim|required|htmlspecialchars|max_length[100]');
      $this->form_validation->set_rules('key','使用Key','trim|required|alpha_dash|is_unique[clickrcms_settings.key]|max_length[20]');
      $this->form_validation->set_rules('value','對應Value','trim|required');
      $this->form_validation->set_rules('group','排序','trim|required');
  }
  
  //刪除設置 根據key
  public function delete($key=''){
   if(!empty($key)){
      $result=$this->settings_mdl->delete_settings($key);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      redirect("admins/settings");
    }else{
      show_error('對不起,參數出錯');
      exit;
    }
  }

  public function mail_test(){
    $protocol= $this->settings['default_email_type']; //email發送方法
    $email_host= $this->settings['email_host']; //Email發出者
    $email_form= $this->settings['email_form']; //發出者名字
    $email_to= $this->settings['email_to']; //發出者名字
    $smtp_host= $this->settings['smtp_host']; //smtp地址smtp_password
    $smtp_password= $this->settings['smtp_password']; //賬戶密碼
    $smtp_port= $this->settings['smtp_port']; //服務器端口

    header('Content-Type: text/html; charset=UTF-8');
    $config['protocol']=($protocol==1)?'mail':'smtp';
    if($protocol==2){
      $config['smtp_host']    = $smtp_host;  
      $config['smtp_user']    = $email_host;  
      $config['smtp_pass']    = $smtp_password;  
      $config['smtp_port']    = $smtp_port;  
    }
    $config['charset']      = 'utf-8';  
    $config['mailtype']     = 'html'; 
    $config['smtp_timeout'] = '5';
    $config['newline'] = "\r\n";
    $content='test';
    $success_message='通知';
    $this->load->library('email',$config);
    $this->email->from($email_host,$email_form);
    $this->email->to($email_to);
    $this->email->subject($success_message);
    $this->email->message($content);
    $this->email->send();
    echo $this->email->print_debugger();
  }
}